package com.atguigu.com.gulimallouth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.com.gulimallouth.feign.MemberFeign;
import com.atguigu.com.gulimallouth.utils.HttpUtils;
import com.atguigu.com.gulimallouth.vo.OauthUser;
import com.atguigu.common.constan.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberVo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class Oauth2Controller {

    @Autowired
    MemberFeign memberFeign;

    //http://127.0.0.1:20000/oauth2/login
    @GetMapping("/oauth2/login")
    public String loginOauth(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {
        Map<String,String> map = new HashMap<>();
        map.put("client_id","4158684645");
        map.put("client_secret","473485c9de8eeb7570064b4e8b1701ba");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://outh.gulimall.com/oauth2/login");
        map.put("code",code);
        String host = "https://api.weibo.com";
        //获取令牌
        HttpResponse response = HttpUtils.doPost(host, "/oauth2/access_token", "POST", null, null, map);
        if (response.getStatusLine().getStatusCode()==200){
            //成功,登录
            //获取参数
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            //String s = JSON.toJSONString(entity);
            OauthUser oauthUser = JSON.parseObject(s, OauthUser.class);
            //远程调用会员服务实现登录
            R r = memberFeign.oauthLogin(oauthUser);
            if (r!=null){
                MemberVo member = r.getData("member", new TypeReference<MemberVo>() {
                });
                //把登陆信息放入session中
                session.setAttribute(AuthServerConstant.LOGIN_USER,member);
            }
            MemberVo attribute = (MemberVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
            System.out.println(attribute.toString());
            return "redirect:http://gulimall.com";
        }else {
            //失败
        }
        return "redirect:http://gulimall.com/index.html";
    }
}
